//
//  ChooseSubUserViewController.m
//  GetPowerDBO
//
//  Created by 周博 on 2017/8/9.
//  Copyright © 2017年 BogoZhou. All rights reserved.
//

#import "ChooseSubUserViewController.h"
#import "ChooseSubUserTableViewCell.h"
#import "YYMGroup.h"

#define kCellName @"ChooseSubUserTableViewCell"

@interface ChooseSubUserViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    
}
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) NSMutableArray *dataArray2;

@property (nonatomic,strong) NSMutableArray *allDataArray;
@property (nonatomic,strong) NSMutableArray *categoryArray;
@end

@implementation ChooseSubUserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self UISetting];
    [self loadData];
}

- (void)UISetting{
    _dataArray = [NSMutableArray array];
    _dataArray2 = [NSMutableArray array];
    _categoryArray = [NSMutableArray array];
    _allDataArray = [NSMutableArray array];
}


- (void)loadData{
    [self.hub hideAnimated:YES];
    
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    
    NSString *oid = kOrganization_id;
    if (oid.integerValue == 1) {//大权限
        oid = nil;
    }
    
    [[AFClient shareInstance] getAllUsersByEid:kAdminUserId oid:oid progressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];

        if ([responseBody[@"code"] integerValue] == 200) {
            
            [_dataArray removeAllObjects];
            [_dataArray2 removeAllObjects];
            [_categoryArray removeAllObjects];
            [_allDataArray removeAllObjects];
            
            NSMutableArray *nameArray = [NSMutableArray array];
            
            //获取所有数据
            for (NSDictionary *dic in responseBody[@"data"]) {
                ChooseUserModel *model = [[ChooseUserModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [nameArray addObject:model.city_name];
                [_allDataArray addObject:model];
            }
            
            //地名去重
            for (unsigned i = 0; i < [nameArray count]; i++){
                if ([_categoryArray containsObject:[nameArray objectAtIndex:i]] == NO){
                    [_categoryArray addObject:[nameArray objectAtIndex:i]];
                }
            }
            
            for (NSInteger i = 0; i < _categoryArray.count; i++) {
                NSString *nameString = _categoryArray[i];
                NSMutableArray *array = [NSMutableArray array];
                
                for (ChooseUserModel *model in _allDataArray) {
                    if ([model.city_name isEqualToString:nameString]) {
                        [array addObject:model];
                    }
                }
                
                [_dataArray2 addObject:array];
            }
            
            for (NSMutableArray *name in _dataArray2) {
                YYMGroup *group1 = [[YYMGroup alloc] initWithItem:name];
                [_dataArray addObject:group1];
            }
            
            [_tableView reloadData];
        }else{
            kAlert(responseBody[@"message"]);
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];

    }];
}

#pragma mark - 点击事件

- (IBAction)backButtonClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}



#pragma mark UITableViewDataSource回调方法
//这是tabview创建多少组的回调
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return _dataArray.count;
}
//这是每个组有多少联系人的回调
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    YYMGroup *group = _dataArray[section];
    return group.isFolded? 0: group.size;
}
//将tabview的cell与数据模型绑定起来
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    //将模型里的数据赋值给cell
    
//    cell.textLabel.text = arr[indexPath.row];
    
    YYMGroup *group = _dataArray[indexPath.section];
    NSArray *arr=group.items;
    
    ChooseSubUserTableViewCell *cell = (ChooseSubUserTableViewCell *)[tableView dequeueReusableCellWithIdentifier:kCellName];
    ChooseUserModel *model = arr[indexPath.row];
    
    cell.labelName.text = model.name;
    cell.labelTel.text = model.mobile;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    YYMGroup *group = _dataArray[indexPath.section];
    NSArray *arr=group.items;

    ChooseUserModel *model = arr[indexPath.row];

    [[NSUserDefaults standardUserDefaults] setValue:model.id forKey:@"userId"];
    [[NSUserDefaults standardUserDefaults] setValue:model.mobile forKey:@"SubMobile"];
    [[NSUserDefaults standardUserDefaults] setValue:model.name forKey:@"SubUserName"];
    [[NSUserDefaults standardUserDefaults] setValue:model.city_name forKey:@"cityName"];
    [[NSUserDefaults standardUserDefaults] setValue:model.admin forKey:@"admin"];
    
    [self.navigationController popViewControllerAnimated:YES];
    
}


#pragma mark UITableViewDelegate回调方法
//对hearderView进行编辑
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    //首先创建一个大的view，nameview
    UIView *nameView=[[UIView alloc]init];
    nameView.backgroundColor = [kColorFrom0x(0xeeeeee) colorWithAlphaComponent:0.3];
    //将分组的名字nameLabel添加到nameview上
    UILabel *nameLabel=[[UILabel alloc]initWithFrame:CGRectMake(40, 0, self.view.frame.size.width, 40)];
    [nameView addSubview:nameLabel];
    nameView.layer.borderWidth=0.2;
    nameView.layer.borderColor=[UIColor grayColor].CGColor;
    NSArray *nameArray=[NSArray arrayWithArray:_categoryArray];
    nameLabel.text=nameArray[section];
    //添加一个button用于响应点击事件（展开还是收起）
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame=CGRectMake(0, 0, self.view.frame.size.width, 40);
    [nameView addSubview:button];
    button.tag = 200 + section;
    [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    //将显示展开还是收起的状态通过三角符号显示出来
    UIImageView *fuhao=[[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 20, 20)];
    fuhao.tag=section;
    [nameView addSubview:fuhao];
    //根据模型里面的展开还是收起变换图片
    YYMGroup *group = _dataArray[section];
    if (group.isFolded==YES) {
        fuhao.image=[UIImage imageNamed:@"右边"];
    }else{
        fuhao.image=[UIImage imageNamed:@"下边"];
    }
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 39, kScreenSize.width, 1)];
    imageView.backgroundColor = kColorFrom0x(0xeeeeee);
    [nameView addSubview:imageView];
    
    //返回nameView
    return nameView;
}


//设置headerView高度
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}
//设置cell的高度
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}
//button的响应点击事件
- (void) buttonClicked:(UIButton *) sender {
    //改变模型数据里面的展开收起状态
    YYMGroup *group2 = _dataArray[sender.tag - 200];
    group2.folded = !group2.isFolded;
    [_tableView reloadData];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
